#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：article_dao.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/7/13 下午1:42 
@explain : 
"""
from sqlalchemy import desc, asc

from app.dao.models import XlxArticle, XlxArticleCategory
from . import tools
from .base_dao import getDatabaseSession


class ArticleQueryDao(object):
    @classmethod
    def get_category_list(cls, page: int = 1, page_size: int = 10) -> tuple[int, list[XlxArticleCategory]]:
        with getDatabaseSession() as session:
            query = session.query(XlxArticleCategory)
            total = query.count()
            # 排序分页
            offset = (page - 1) * page_size
            query = query.order_by(asc(XlxArticleCategory.sort_id)).offset(offset).limit(page_size)
            # 查询记录
            result = query.all()
        return total, result

    @classmethod
    def find_by_id(cls, id: int) -> XlxArticle:
        with getDatabaseSession() as session:
            query = session.query(XlxArticle)
            query = query.filter(XlxArticle.id == id)
            result = query.first()
        return result

    @classmethod
    def get_category_by_id(cls, id: int) -> XlxArticleCategory:
        with getDatabaseSession() as session:
            query = session.query(XlxArticleCategory)
            query = query.filter(XlxArticleCategory.id == id)
            result = query.first()
        return result

    @classmethod
    def list(cls, field_names: list = [], page: int = 1, page_size: int = 10, **kwargs) -> tuple[int, list[XlxArticle]]:
        with getDatabaseSession() as session:
            if len(field_names) > 0:
                valid_fields = [getattr(XlxArticle, field_name, None) for field_name in field_names if
                                hasattr(XlxArticle, field_name)]
                if not valid_fields:
                    raise ValueError("No valid fields to select.")
                query = session.query(*valid_fields)
            else:
                query = session.query(XlxArticle)

            query = tools.build_query(query, XlxArticle, **kwargs)
            total = query.count()
            # 排序分页
            offset = (page - 1) * page_size
            query = query.order_by(desc(XlxArticle.addtime)).offset(offset).limit(page_size)
            # 查询记录
            result = query.all()
        return total, result


class ArticleOperateDao(object):
    @classmethod
    def save(cls, data: dict) -> XlxArticle:
        with getDatabaseSession() as session:
            new_data = XlxArticle(**data)
            session.add(new_data)
            session.flush()
            session.commit()
        return new_data

    @classmethod
    def updata(cls, data: dict) -> XlxArticle:
        with getDatabaseSession() as session:
            query = session.query(XlxArticle).filter(XlxArticle.id == data['id']).first()
            for key, value in data.items():
                if value:
                    if hasattr(XlxArticle, key):  # 确保属性存在于模型中
                        setattr(query, key, value)
            session.commit()
        return query

    @classmethod
    def delete(cls, id: int) -> bool:
        with getDatabaseSession() as session:
            query = session.query(XlxArticle).filter(XlxArticle.id == id).first()
            if query:
                session.delete(query)
                session.commit()
                return True
            else:
                return False

    @classmethod
    def category_updata(cls, data: dict) -> XlxArticleCategory:
        with getDatabaseSession() as session:
            query = session.query(XlxArticleCategory).filter(XlxArticleCategory.id == data['id']).first()
            for key, value in data.items():
                if value:
                    if hasattr(XlxArticleCategory, key):  # 确保属性存在于模型中
                        setattr(query, key, value)
            session.commit()
        return query

    @classmethod
    def category_save(cls, data: dict) -> XlxArticleCategory:
        with getDatabaseSession() as session:
            new_data = XlxArticleCategory(**data)
            session.add(new_data)
            session.flush()
            session.commit()
        return new_data

    @classmethod
    def category_del(cls, id: int) -> bool:
        """删除用户数据"""
        with getDatabaseSession() as session:
            group = session.query(XlxArticleCategory).filter(XlxArticleCategory.id == id).first()
            if group:
                session.delete(group)
                session.commit()
                return True
            else:
                return False
